<?php


namespace app\miniProgram\controller;




use systematic\Systematic;
use think\facade\Config;
use think\facade\Db;
use think\Request;

class Base
{
protected $userInfo=[];
protected $param=[];
protected $auth=false;
public function __construct(Request $request = null)
{
    //检测js预请求就停止
    if ($_SERVER['REQUEST_METHOD']=='OPTIONS') {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
        header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
        exit();
    }
    $this->param = $request->post();
    //获取登陆用户的信息
    $this->userInfo = $this->getLoginUerInfo();
}


    public function jump($return, $message="", $source=''){
        if (is_array($return)) {
            $code = $return['code'];
            $message = $return['message'];
            $source = isset($return['data'])?$return['data']:[];
        } else {
            $code = $return;
        }

        if($code != 1 && (empty($source) || count($source) <= 0)){
            $source = [];
        }
        if (!is_numeric($code)){
            return false;
        }
        $return_code = config("app.return_code");
        //http_response_code($code);    //设置返回头部
        $return_data = [
            'code' => $return_code[(int)$code]['code'],
            'msg' => $message?$message:$return_code[(int)$code]["message"],
            'data' => $source
        ];
        $origin = $_SERVER['HTTP_ORIGIN'] ?? '*';
        header('Content-Type:application/json; charset=utf-8');
        header('Access-Control-Allow-Origin:'.$origin);
        header('Access-Control-Allow-Methods:*');
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Allow-Headers: Authorization,Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,Access-Control-Allow-Credentials,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Cache-Webcdn');
        if(isset($return["status"])){
            exit(json_encode($return_data,JSON_UNESCAPED_UNICODE));
        }
        return json($return_data);
    }

    private function getLoginUerInfo(){
        $header = request()->header();
        $authorizationStr = isset($header["authorization"]) ? $header["authorization"] : '';
        $userInfo = [];
        if(!empty($authorizationStr)){
            $tokenBody = !is_null($authorizationStr) ? explode(' ', $authorizationStr) : [];
            $token = explode(':', base64_decode($tokenBody[1]));
            $username = $token[0];
            $password = $token[1];
            $cId = $token[2];
            $comInfo=Db::name('company')->where('id',$cId)->find();
            $comConnect=[
                'type'               =>  'mysql',
                'hostname'           =>  $comInfo['ip'],
                'database'           =>  $comInfo['databaseName'],
                'username'           =>  $comInfo['username'],
                'password'           =>  $comInfo['password'],
                'hostport'           =>  '3306',
                // 数据库表前缀
                'prefix'             =>  'fy_',
                // 数据库连接参数
                'params'          => [],
                // 数据库编码默认采用utf8mb4
                'charset'         => 'utf8mb4',
                // 数据库调试模式
                'debug'           => false,
                // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
                'deploy'          => 0,
                // 数据库读写是否分离 主从式有效
                'rw_separate'     => false,
                // 读写分离后 主服务器数量
                'master_num'      => 1,
                // 指定从服务器序号
                'slave_no'        => '',
                // 是否严格检查字段是否存在
                'fields_strict'   => true,
                // 是否需要断线重连
                'break_reconnect' => false,
                // 监听SQL
                'trigger_sql'     => true,
                // 开启字段缓存
                'fields_cache'    => false,
            ];
            $config=Config::get('database');
            $config['connections']['company']=$comConnect;
            Config::set($config,'database');
            $userInfo=Db::connect('company')->name('Admin')->where('username',$username)
                ->where('salt',$password)->where('status',1)->find();
        }
        return $userInfo;
    }
    public function getDJBHBuySql($table='',$field='orderNum',$text='')
    {

        try {
            $code=Db::connect('company')->name($table)
                ->where('status','>',-1)
                ->where($field,'like',$text.date('Ym').'%')
                ->order("{$field} DESC")
                ->value($field);

        }catch (\Exception $exception){
            $code='';
        }
        if ($code){
            $code=str_replace($text,'',$code);
            $code=(int)$code+1;
        }else{
            $num=0;
            if ($num){
                $num+=1;
            }else{
                $num=1;
            }
            $str=(string)(1000+$num);
            $code=substr($str, 1);
            $code=date('Ym').$code;
        }
        return $text.$code;
    }
}